"""
教师管理路由 - 仅限自己课程的学生和课程
"""
from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.blueprints.api import api_bp
from app.models.user import User, StudentProfile
from app.models.course import Course, CourseTag
from app.models.student_course import StudentCourse
from app.models.log import SystemLog
from app.extensions import db
from datetime import datetime
from decimal import Decimal
import pandas as pd
import io


@api_bp.route('/teacher/courses/<int:course_id>/students/<int:student_id>/grade', methods=['PUT'])
@jwt_required()
def update_student_grade(course_id, student_id):
    """教师更新学生成绩（仅限自己的课程）"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'teacher':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        # 验证课程是否属于该教师
        course = Course.query.filter_by(id=course_id, instructor_id=current_user_id).first()
        if not course:
            return jsonify({
                'success': False,
                'error': 'Course not found or you are not the instructor'
            }), 404
        
        # 查找学生选课记录
        student_course = StudentCourse.query.filter_by(
            course_id=course_id,
            student_id=student_id
        ).first()
        
        if not student_course:
            return jsonify({
                'success': False,
                'error': 'Student not enrolled in this course'
            }), 404
        
        data = request.get_json()
        
        # 更新成绩
        if 'score' in data:
            student_course.score = float(data['score'])
            # 自动计算等级
            score = float(data['score'])
            if score >= 90:
                student_course.letter_grade = 'A'
            elif score >= 80:
                student_course.letter_grade = 'B'
            elif score >= 70:
                student_course.letter_grade = 'C'
            elif score >= 60:
                student_course.letter_grade = 'D'
            else:
                student_course.letter_grade = 'F'
        
        if 'midterm_score' in data:
            student_course.midterm_score = float(data['midterm_score'])
        
        if 'final_score' in data:
            student_course.final_score = float(data['final_score'])
        
        if 'attendance_rate' in data:
            student_course.attendance_rate = float(data['attendance_rate'])
        
        if 'attended' in data:
            student_course.attended = int(data['attended'])
            # 自动计算出勤率
            if student_course.total_classes:
                student_course.attendance_rate = (student_course.attended / student_course.total_classes) * 100
        
        if 'status' in data:
            student_course.status = data['status']
        
        student_course.graded_at = datetime.utcnow()
        student_course.updated_at = datetime.utcnow()
        
        # 记录日志
        log = SystemLog(
            user_id=current_user_id,
            action='update_grade',
            resource_type='student_course',
            resource_id=str(student_course.id),
            ip_address=request.remote_addr,
            status='success',
            level='INFO',
            message=f'Updated grade for student {student_id} in course {course_id}'
        )
        db.session.add(log)
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Grade updated successfully',
            'data': student_course.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/teacher/courses/<int:course_id>/students', methods=['GET'])
@jwt_required()
def get_teacher_course_students(course_id):
    """教师获取课程的学生列表（教师可查看所有课程，但只能编辑自己的）"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'teacher':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        # 获取课程（只能查看自己的课程）
        course = Course.query.filter_by(
            id=course_id,
            instructor_id=current_user_id
        ).first()
        
        if not course:
            return jsonify({
                'success': False,
                'error': 'Course not found or you are not the instructor'
            }), 404
        
        # 获取学生列表（添加空值检查）
        students = []
        for sc in course.student_courses:
            # 跳过无效的学生记录
            if not sc.student:
                continue
            
            try:
                student_data = {
                    'id': sc.student.id,
                    'username': sc.student.username,
                    'student_id': sc.student.student_profile.student_id if sc.student.student_profile else None,
                    'last_name': sc.student.last_name or '',
                    'first_name': sc.student.first_name or '',
                    'email': sc.student.email or '',
                    'phone': sc.student.phone or '',
                    'score': float(sc.score) if sc.score else None,
                    'midterm_score': float(sc.midterm_score) if sc.midterm_score else None,
                    'final_score': float(sc.final_score) if sc.final_score else None,
                    'letter_grade': sc.letter_grade,
                    'status': sc.status,
                    'attendance_rate': float(sc.attendance_rate) if sc.attendance_rate else None,
                    'attended': sc.attended,
                    'total_classes': sc.total_classes,
                    'student_course_id': sc.id
                }
                students.append(student_data)
            except Exception as e:
                # 跳过有问题的记录，记录错误但不中断
                print(f"Warning: Failed to process student record {sc.id}: {str(e)}")
                continue
        
        # 按成绩排序
        students.sort(key=lambda x: x['score'] if x['score'] else 0, reverse=True)
        
        course_data = course.to_dict()
        course_data['can_edit'] = True  # 当前用户是课程教师，可编辑
        
        return jsonify({
            'success': True,
            'data': {
                'course': course_data,
                'students': students,
                'total': len(students),
                'can_edit': True  # 当前用户是课程教师，可编辑
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/teacher/my-courses', methods=['GET'])
@jwt_required()
def get_my_courses():
    """获取教师自己的课程列表（带管理权限）"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'teacher':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        courses = Course.query.filter_by(instructor_id=current_user_id).all()
        
        courses_data = []
        for course in courses:
            course_dict = course.to_dict()
            
            # 添加统计信息
            total_students = StudentCourse.query.filter_by(course_id=course.id).count()
            completed = StudentCourse.query.filter_by(course_id=course.id, status='completed').count()
            
            course_dict['total_students'] = total_students
            course_dict['completed_students'] = completed
            course_dict['can_edit'] = True  # 标记教师有编辑权限
            
            courses_data.append(course_dict)
        
        return jsonify({
            'success': True,
            'data': courses_data,
            'total': len(courses_data)
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/teacher/my-students/search', methods=['GET'])
@jwt_required()
def search_teacher_students():
    """教师搜索自己课程中的学生（不同于全局学生搜索）"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'teacher':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        keyword = request.args.get('q', '')
        
        if not keyword:
            return jsonify({
                'success': False,
                'error': 'Search keyword required'
            }), 400
        
        # 获取教师的所有课程
        teacher_courses = Course.query.filter_by(instructor_id=current_user_id).all()
        course_ids = [c.id for c in teacher_courses]
        
        # 搜索这些课程中的学生
        student_courses = StudentCourse.query.filter(
            StudentCourse.course_id.in_(course_ids)
        ).join(User).filter(
            db.or_(
                User.username.like(f'%{keyword}%'),
                User.email.like(f'%{keyword}%')
            )
        ).all()
        
        results = []
        seen_students = set()
        
        for sc in student_courses:
            if sc.student_id not in seen_students:
                seen_students.add(sc.student_id)
                results.append({
                    'student_id': sc.student_id,
                    'username': sc.student.username,
                    'name': f"{sc.student.last_name}{sc.student.first_name}",
                    'email': sc.student.email,
                    'courses': [c.course.name for c in StudentCourse.query.filter(
                        StudentCourse.student_id == sc.student_id,
                        StudentCourse.course_id.in_(course_ids)
                    ).all()]
                })
        
        return jsonify({
            'success': True,
            'data': results,
            'total': len(results)
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/teacher/courses', methods=['POST'])
@jwt_required()
def create_teacher_course():
    """教师创建新课程"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'teacher':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['course_code', 'course_name', 'credits']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'success': False,
                    'error': f'Missing required field: {field}'
                }), 400
        
        # 检查课程代码是否已存在
        existing_course = Course.query.filter_by(code=data['course_code']).first()
        if existing_course:
            return jsonify({
                'success': False,
                'error': 'Course code already exists'
            }), 400
        
        # 创建新课程
        course = Course(
            code=data['course_code'],
            name=data['course_name'],
            credits=Decimal(str(data['credits'])),
            instructor_id=current_user_id,  # 自动设置为当前教师
            department=data.get('department', ''),
            description=data.get('description', ''),
            semester=data.get('semester', ''),
            max_students=data.get('max_students', 100)
        )
        
        db.session.add(course)
        db.session.flush()
        
        # 从 schedule 文本提取时间标签（用于冲突检测）
        schedule_text = (data.get('schedule') or '').strip()
        if schedule_text:
            import re
            cn_map = {'一':1,'二':2,'三':3,'四':4,'五':5,'六':6,'日':7,'天':7}
            m = re.search(r'周([一二三四五六日天])\s*(\d+)(?:\s*-\s*(\d+))?', schedule_text)
            if m:
                dow = cn_map.get(m.group(1))
                start = int(m.group(2))
                end = int(m.group(3) or start)
                db.session.add(CourseTag(course_id=course.id, tag=f'dow-{dow}'))
                db.session.add(CourseTag(course_id=course.id, tag=f'slot-{start}-{end}'))
        
        db.session.commit()
        
        # 记录日志
        log = SystemLog(
            user_id=current_user_id,
            action='create',
            resource_type='course',
            resource_id=str(course.id),
            ip_address=request.remote_addr,
            status='success',
            level='INFO',
            message=f'Teacher created course {course.code}'
        )
        db.session.add(log)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Course created successfully',
            'data': course.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/teacher/courses/<int:course_id>', methods=['PUT'])
@jwt_required()
def update_teacher_course(course_id):
    """教师更新自己的课程信息"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'teacher':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        # 验证课程是否属于该教师
        course = Course.query.filter_by(id=course_id, instructor_id=current_user_id).first()
        if not course:
            return jsonify({
                'success': False,
                'error': 'Course not found or you are not the instructor'
            }), 404
        
        data = request.get_json()
        
        # 更新课程信息
        if 'course_name' in data:
            course.name = data['course_name']
        if 'credits' in data:
            course.credits = Decimal(str(data['credits']))
        if 'department' in data:
            course.department = data['department']
        if 'description' in data:
            course.description = data['description']
        if 'semester' in data:
            course.semester = data['semester']
        if 'academic_year' in data:
            course.academic_year = data['academic_year']
        if 'semester_term' in data:
            course.semester_term = data['semester_term']
        if 'max_students' in data:
            course.max_students = data['max_students']
        
        course.updated_at = datetime.utcnow()
        db.session.commit()
        
        # 记录日志
        log = SystemLog(
            user_id=current_user_id,
            action='update',
            resource_type='course',
            resource_id=str(course_id),
            ip_address=request.remote_addr,
            status='success',
            level='INFO',
            message=f'Teacher updated course {course.code}'
        )
        db.session.add(log)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Course updated successfully',
            'data': course.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/teacher/courses/<int:course_id>/students', methods=['POST'])
@jwt_required()
def add_student_to_course(course_id):
    """教师向自己的课程添加学生"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'teacher':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        # 验证课程是否属于该教师
        course = Course.query.filter_by(id=course_id, instructor_id=current_user_id).first()
        if not course:
            return jsonify({
                'success': False,
                'error': 'Course not found or you are not the instructor'
            }), 404
        
        # 获取请求数据并增强错误处理
        data = request.get_json()
        
        # 检查是否成功解析JSON
        if data is None:
            return jsonify({
                'success': False,
                'error': 'Invalid JSON data or Content-Type header missing',
                'content_type': request.content_type,
                'data': request.data.decode('utf-8') if request.data else 'No data'
            }), 400
        
        student_id = data.get('student_id')
        
        if not student_id:
            return jsonify({
                'success': False,
                'error': 'Student ID is required',
                'received_data': data
            }), 400
        
        # 验证学生是否存在
        student = User.query.filter_by(id=student_id, role='student').first()
        if not student:
            return jsonify({
                'success': False,
                'error': 'Student not found'
            }), 404
        
        # 获取学生profile
        if not student.student_profile:
            return jsonify({
                'success': False,
                'error': 'Student profile not found'
            }), 404
        
        student_profile_id = student.student_profile.id
        
        # 检查学生是否已经在课程中
        existing_enrollment = StudentCourse.query.filter_by(
            course_id=course_id,
            student_id=student_profile_id
        ).first()
        
        if existing_enrollment:
            return jsonify({
                'success': False,
                'error': 'Student already enrolled in this course'
            }), 400
        
        # 检查课程是否已满
        current_enrollment = StudentCourse.query.filter_by(course_id=course_id).count()
        if current_enrollment >= course.max_students:
            return jsonify({
                'success': False,
                'error': 'Course is full'
            }), 400
        
        # 添加学生到课程
        student_course = StudentCourse(
            student_id=student_profile_id,
            course_id=course_id,
            enrollment_date=datetime.utcnow(),
            status='enrolled',  # 使用正确的ENUM值
            total_classes=30,  # 默认总课时
            attended=0,
            attendance_rate=Decimal('0.00')
        )
        
        db.session.add(student_course)
        db.session.commit()
        
        # 记录日志
        log = SystemLog(
            user_id=current_user_id,
            action='create',
            resource_type='enrollment',
            resource_id=str(student_course.id),
            ip_address=request.remote_addr,
            status='success',
            level='INFO',
            message=f'Teacher added student {student.username} to course {course.code}'
        )
        db.session.add(log)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Student added to course successfully',
            'data': {
                'id': student_course.id,
                'student_id': student_id,
                'student_name': f"{student.last_name}{student.first_name}",
                'course_id': course_id,
                'enrollment_date': student_course.enrollment_date.isoformat()
            }
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/teacher/courses/<int:course_id>/students/<int:student_id>', methods=['DELETE'])
@jwt_required()
def remove_student_from_course(course_id, student_id):
    """教师从自己的课程中移除学生"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'teacher':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        # 验证课程是否属于该教师
        course = Course.query.filter_by(id=course_id, instructor_id=current_user_id).first()
        if not course:
            return jsonify({
                'success': False,
                'error': 'Course not found or you are not the instructor'
            }), 404
        
        # 查找选课记录
        student_course = StudentCourse.query.filter_by(
            course_id=course_id,
            student_id=student_id
        ).first()
        
        if not student_course:
            return jsonify({
                'success': False,
                'error': 'Student not enrolled in this course'
            }), 404
        
        student = User.query.get(student_id)
        student_name = f"{student.last_name}{student.first_name}" if student else "Unknown"
        
        db.session.delete(student_course)
        db.session.commit()
        
        # 记录日志
        log = SystemLog(
            user_id=current_user_id,
            action='delete',
            resource_type='enrollment',
            resource_id=str(student_course.id),
            ip_address=request.remote_addr,
            status='success',
            level='WARNING',
            message=f'Teacher removed student {student_name} from course {course.code}'
        )
        db.session.add(log)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Student removed from course successfully'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/teacher/students/search', methods=['GET'])
@jwt_required()
def search_students_for_teacher():
    """教师搜索学生（用于添加到课程）"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'teacher':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        # 获取查询参数
        query = request.args.get('q', '').strip()
        course_id = request.args.get('course_id', type=int)
        
        # 构建查询
        students_query = User.query.filter_by(role='student')
        
        # 搜索条件
        if query:
            # 关联 StudentProfile 以便搜索 student_id
            students_query = students_query.join(StudentProfile, User.id == StudentProfile.user_id, isouter=True)
            students_query = students_query.filter(
                db.or_(
                    User.username.like(f'%{query}%'),
                    User.first_name.like(f'%{query}%'),
                    User.last_name.like(f'%{query}%'),
                    User.email.like(f'%{query}%'),
                    StudentProfile.student_id.like(f'%{query}%'),  # 学号搜索
                    db.func.concat(User.last_name, User.first_name).like(f'%{query}%')  # 完整姓名搜索
                )
            )
        
        students = students_query.limit(50).all()
        
        # 如果指定了课程ID，标记哪些学生已在课程中
        enrolled_student_ids = set()
        if course_id:
            enrolled = StudentCourse.query.filter_by(course_id=course_id).all()
            enrolled_student_ids = {sc.student_id for sc in enrolled}
        
        results = []
        for student in students:
            student_profile = student.student_profile
            results.append({
                'id': student.id,  # 用户ID - 用于添加到课程
                'username': student.username,
                'student_id': student_profile.student_id if student_profile else None,  # 学号 - 仅用于显示
                'name': f"{student.last_name}{student.first_name}",
                'email': student.email,
                'enrolled': student.id in enrolled_student_ids
            })
        
        return jsonify({
            'success': True,
            'data': results,
            'total': len(results)
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/teacher/courses/<int:course_id>/students/batch-import', methods=['POST'])
@jwt_required()
def batch_import_students(course_id):
    """教师批量导入学生到自己的课程"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'teacher':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        # 验证课程是否属于该教师
        course = Course.query.filter_by(id=course_id, instructor_id=current_user_id).first()
        if not course:
            return jsonify({
                'success': False,
                'error': 'Course not found or you are not the instructor'
            }), 404
        
        # 检查是否有上传的文件
        if 'file' not in request.files:
            return jsonify({
                'success': False,
                'error': 'No file uploaded'
            }), 400
        
        file = request.files['file']
        
        if file.filename == '':
            return jsonify({
                'success': False,
                'error': 'No file selected'
            }), 400
        
        # 检查文件类型
        if not file.filename.lower().endswith(('.csv', '.xlsx', '.xls')):
            return jsonify({
                'success': False,
                'error': 'Invalid file type. Please upload CSV or Excel file'
            }), 400
        
        # 读取文件
        try:
            if file.filename.lower().endswith('.csv'):
                df = pd.read_csv(io.BytesIO(file.read()), encoding='utf-8')
            else:
                df = pd.read_excel(io.BytesIO(file.read()))
        except Exception as e:
            return jsonify({
                'success': False,
                'error': f'Failed to read file: {str(e)}'
            }), 400
        
        # 验证必需的列
        required_columns = ['student_id']  # 必须有学号列
        missing_columns = [col for col in required_columns if col not in df.columns]
        
        if missing_columns:
            return jsonify({
                'success': False,
                'error': f'Missing required columns: {", ".join(missing_columns)}. Required: student_id'
            }), 400
        
        # 统计结果
        success_count = 0
        failed_count = 0
        skipped_count = 0
        errors = []
        
        # 获取当前课程的选课人数
        current_enrollment = StudentCourse.query.filter_by(course_id=course_id).count()
        
        # 遍历每一行
        for index, row in df.iterrows():
            try:
                student_id_str = str(row['student_id']).strip()
                
                if not student_id_str or student_id_str == 'nan':
                    skipped_count += 1
                    errors.append(f'Row {index + 2}: Empty student_id')
                    continue
                
                # 通过student_id查找学生的StudentProfile
                student_profile = StudentProfile.query.filter_by(student_id=student_id_str).first()
                
                if not student_profile:
                    failed_count += 1
                    errors.append(f'Row {index + 2}: Student {student_id_str} not found')
                    continue
                
                # 获取用户ID
                student_user = student_profile.user
                if not student_user or student_user.role != 'student':
                    failed_count += 1
                    errors.append(f'Row {index + 2}: Invalid student user for {student_id_str}')
                    continue
                
                # 检查学生是否已在课程中
                existing = StudentCourse.query.filter_by(
                    course_id=course_id,
                    student_id=student_user.id  # 修复：使用 users.id
                ).first()
                
                if existing:
                    skipped_count += 1
                    errors.append(f'Row {index + 2}: Student {student_id_str} already enrolled')
                    continue
                
                # 检查课程是否已满
                if current_enrollment + success_count >= course.max_students:
                    failed_count += 1
                    errors.append(f'Row {index + 2}: Course is full (max: {course.max_students})')
                    continue
                
                # 创建选课记录
                student_course = StudentCourse(
                    student_id=student_user.id,  # 修复：使用 users.id 而不是 student_profile.id
                    course_id=course_id,
                    enrollment_date=datetime.utcnow(),
                    status='enrolled',  # 使用正确的ENUM值
                    total_classes=30,
                    attended=0,
                    attendance_rate=Decimal('0.00')
                )
                
                db.session.add(student_course)
                success_count += 1
                
            except Exception as e:
                failed_count += 1
                errors.append(f'Row {index + 2}: {str(e)}')
                continue
        
        # 提交数据库更改
        try:
            db.session.commit()
            
            # 记录日志
            log = SystemLog(
                user_id=current_user_id,
                action='batch_import',
                resource_type='enrollment',
                resource_id=str(course_id),
                ip_address=request.remote_addr,
                status='success',
                level='INFO',
                message=f'Batch imported students to course {course.code}: success={success_count}, failed={failed_count}, skipped={skipped_count}'
            )
            db.session.add(log)
            db.session.commit()
            
        except Exception as e:
            db.session.rollback()
            return jsonify({
                'success': False,
                'error': f'Database error: {str(e)}'
            }), 500
        
        return jsonify({
            'success': True,
            'message': 'Batch import completed',
            'data': {
                'total': len(df),
                'success': success_count,
                'failed': failed_count,
                'skipped': skipped_count,
                'errors': errors[:20]  # 只返回前20条错误
            }
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/teacher/courses/<int:course_id>/students/import-template', methods=['GET'])
@jwt_required()
def download_batch_import_template(course_id):
    """Teacher downloads batch import students template"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if user.role != 'teacher':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        # Verify course belongs to this teacher
        course = Course.query.filter_by(id=course_id, instructor_id=current_user_id).first()
        if not course:
            return jsonify({
                'success': False,
                'error': 'Course not found or you are not the instructor'
            }), 404
        
        # Return CSV template content
        template_content = 'student_id\n2021000001\n2021000002\n2021000003'
        
        return jsonify({
            'success': True,
            'data': {
                'filename': f'batch_import_students_template_{course.code}.csv',
                'content': template_content
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500
